/**
 * @FileName: Receiver02.java
 * @Package: com.rabbitmq
 * @author lig134
 * @created 2017/3/9 13:02
 * <p>
 * Copyright 2015 ziroom
 */
package com.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <p></p>
 *
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *加消息确认收到
 * @author lig134
 * @since 1.0
 * @version 1.0
 */
public class Receiver02 {

    public static  void  main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory conn=new ConnectionFactory();
        conn.setHost("master");
        conn.setPort(5672);
        conn.setUsername("ligen");
        conn.setPassword("ligen");
//        conn.setVirtualHost("/");
        Connection conn1=conn.newConnection();

        Channel channel=conn1.createChannel();

        String queueName="queue01";
        boolean durable=false;
        channel.queueDeclare(queueName,durable,false,false,null);

        //上边和send保持一致
        QueueingConsumer consumer=new QueueingConsumer(channel);
        //与1的特点，取消autoAck
        boolean autoAck=false;
        channel.basicConsume(queueName,autoAck,consumer);
        channel.basicQos(1);
        System.out.println("receiving message ...");
        //循环获取消息
        while (true){
            //获取消息，如果没有消息，一直阻塞
            QueueingConsumer.Delivery delivery=consumer.nextDelivery();
            String msg=new String(delivery.getBody());

            //确认消息，已经收到
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
            System.out.println("receive message["+msg+"] from"+queueName);
        }
    }
}